/**
 * The preload script runs before `index.html` is loaded
 * in the renderer. It has access to web APIs as well as
 * Electron's renderer process modules and some polyfilled
 * Node.js functions.
 *
 * https://www.electronjs.org/docs/latest/tutorial/sandbox
 */
const { contextBridge, ipcRenderer } = require("electron");

window.addEventListener("DOMContentLoaded", () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector);
    if (element) element.innerText = text;
  };

  for (const type of ["chrome", "node", "electron"]) {
    replaceText(`${type}-version`, process.versions[type]);
  }
});

contextBridge.exposeInMainWorld("electronAPI", {
  // WebView相关API
  onOpenWebViewDevTools: (callback) =>
    ipcRenderer.on("open-webview-devtools", callback),
  onRefreshWebIgnoreCache: (callback) =>
    ipcRenderer.on("refresh-webview-ignorecache", callback),
  onToggleChatroom: (callback) =>
    ipcRenderer.on("toggle-webview-chatroom", callback),
  getWebviewPreloadPath: () => ipcRenderer.invoke("get-webview-preload-path"),
  onToWebViewPaste: (callback) => {
    ipcRenderer.on("to-webview-paste", (_, data, extraData) => callback(data, extraData));
  },
  
  // 工具箱相关API
  onToogleToolbox: (callback) =>
    ipcRenderer.on("toggle-toolbox", (_, data) => callback(data)),
  
  // 截图相关API
  sendToScreenHandle: (data) => ipcRenderer.send("hotkey-screenshot", data),
  
  // 文件操作API
  checkFileExists: (filePath) => ipcRenderer.invoke("check-file-exists", filePath),
  openFileLocation: (filePath) => ipcRenderer.send("open-file-location", filePath),
  
  // 文件下载相关API
  onDownloadProgress: (callback) =>
    ipcRenderer.on("download-progress", (_, data) => callback(data)),
  removeDownloadProgressListener: () =>
    ipcRenderer.removeAllListeners("download-progress"),
  cancelDownload: (downloadId) => ipcRenderer.send("cancel-download", downloadId),
  readDownloadHistory: () => ipcRenderer.invoke('read-download-history'),
  writeDownloadHistory: (history) => ipcRenderer.invoke('write-download-history', history),
  
  // 应用更新相关API
  onShowDownloadProgress: (callback) =>
    ipcRenderer.on("show-download-progress", callback),
  onUpdateDownloadProgress: (callback) =>
    ipcRenderer.on("update-download-progress", (_, data) => callback(data)),
  onHideDownloadProgress: (callback) =>
    ipcRenderer.on("hide-download-progress", callback),
  
  // 自动更新相关API
  updater: {
    getAppVersion: () => ipcRenderer.invoke("get-app-version"),
    checkForUpdates: () => ipcRenderer.invoke("check-for-updates"),
    downloadUpdate: () => ipcRenderer.invoke("download-update"),
    installUpdate: () => ipcRenderer.invoke("install-update"),
    getUpdateStatus: () => ipcRenderer.invoke("get-update-status"),
    getUpdateConfig: () => ipcRenderer.invoke("get-update-config"),
    getUpdateDownloadPath: () => ipcRenderer.invoke("get-update-download-path"),
    onUpdateStatus: (callback) =>
      ipcRenderer.on("update-status", (_, data) => {
        if (data && typeof data === 'object' && data.type) {
          callback(data);
        } else {
          console.warn('收到无效的更新状态数据:', data);
        }
      }),
    removeUpdateStatusListener: () =>
      ipcRenderer.removeAllListeners("update-status"),
  },
});
